import React, { FC, useEffect, useState, ReactElement } from 'react';
import { connect } from 'react-redux';
import { useHistory } from 'react-router-dom';
import { Card, Icon, ActionSheet } from 'antd-mobile-v2';
import {
  MyStatus,
  TabIds,
  Actions,
  ActionsText,
  ApprovalColor,
  ProcessActions,
  ApprovalStatus,
  TaskStatus
} from '../constants';
import ColumnDetail from '@/components/column';
import FormRender from '@/plugins/form/form-render';
import H5Components from '@/plugins/form/form-components';
import styles from './index.module.less';
import Image from '@/components/Image/TokenImage';
import { IGaeaInstance } from '@/plugins/form/types';
import {
  parseValueForDetail,
  parseFormData,
  parseValue
} from '@/plugins/form/form-render/utils/detail-parser';
// import _ from 'lodash';
import ProcessList from './process';
import { WrappedFormClass } from 'rc-form';
import { IApprovalItem, HistoryTask } from '../type';
import cancelImg from '@/assets/approval/cancel-2.png';
import rejectImg from '@/assets/approval/reject.png';
import { AppRefresh, AppToast } from '@/utils/app-func';
import { ConnectProps } from 'typings/connect';
import { SUCCESS_CODE } from '@/services/constant';

export interface IApprovalDetail extends ConnectProps {
  task: IApprovalItem;
  recordId: string;
  form?: WrappedFormClass<{}>;
  myStatus?: MyStatus;
  srvTime?: number;
  onRefreshStatus?: () => void;
}
// 审批业务首页
const ApprovalDetail: FC<IApprovalDetail> = (props) => {
  const history = useHistory();
  const [formParsedG, setFormParsed] = useState<{
    [index: string]: IGaeaInstance;
  }>();
  const [formValuesG, setFormValues] = useState<{
    [index: string]: any;
  }>();
  const [promptText, setNoticeText] = useState<string>();
  const [historyTaskList, setHistoryTaskList] = useState<HistoryTask[]>();

  const task = props.task;
  let isAction = false;
  useEffect(() => {
    getHistoryTaskList();

    // 合并值和json
    let formParsed = parseFormData(
      props.task?.formData.formModelData,
      props.myStatus === MyStatus.MyApply ? 'all' : props.task?.taskDefKey, //props.task.taskDefKey 这里做了判断 如果是我申请的则使用默认id
      false
    );
    const formValues = parseValue(props.task?.formData.formValues);
    formParsed = parseValueForDetail(formParsed, formValues);
    for (const key in formParsed) {
      // 说明文字不显示
      if (formParsed[key].gaeaKey === 'gaea-help-text') {
        delete formParsed[key];
      }
    }
    // 异常情况提示（待我审批）
    if (props.myStatus == 1) {
      const exception = props?.task?.formData?.exception;
      if (exception && exception != '无') {
        setNoticeText('该申请单有异常情况，请留意查看');
      }
    }
    // console.log('formParsed', formParsed);
    setFormParsed(formParsed);
    setFormValues(formValues);
  }, [props.task]);

  const getHistoryTaskList = () => {
    if (props.dispatch && props.task?.innerProcDefId) {
      props
        .dispatch({
          type: 'capproval/getHistoryTaskList',
          payload: {
            innerProcDefId: props.task?.innerProcDefId,
            procInstId: props.task?.procInstId
          }
        })
        .then((res?: any) => {
          if (res && res.status == SUCCESS_CODE) {
            console.log('tasklist:', res.data);
            setHistoryTaskList(res.data);
          }
        });
    }
  };

  const openActionModal = async (action: Actions) => {
    const tabId = props.myStatus === MyStatus.MyApply ? TabIds.MyApply : TabIds.ToApproval;
    const actionName = action === Actions.Reject ? ActionsText.Reject : ActionsText.Agree;
    history.push(
      `/approval/action?recordId=${props.recordId}&tabId=${tabId}&action=${actionName}&type=fromDetail`
    );
  };

  const agree = () => {
    openActionModal(Actions.Agree);
  };

  const recall = async () => {
    const params: any = {
      action: ProcessActions.Recall,
      procRecordId: props.task.procRecordId
    };
    if (props.dispatch) {
      const res = await props.dispatch({
        type: 'capproval/changeMyApplyProcess',
        payload: params
      });
      if (res && res.status === SUCCESS_CODE) {
        return true;
      }
    }
    return false;
  };

  const renderActions = () => {
    return [
      <span
        key="reject"
        className={styles.btn}
        onClick={() => {
          openActionModal(Actions.Reject);
        }}
      >
        <Icon type="cross-circle" size="sm" className={styles.btnIcon} />
        <span className={styles.btnText}>拒绝</span>
      </span>,
      <span
        key="agree"
        className={styles.btn}
        onClick={() => {
          agree();
        }}
      >
        <Icon type="check-circle-o" size="sm" className={styles.btnIcon} />
        <span className={styles.btnText}>同意</span>
      </span>
    ];
  };

  const renderMyApplyActions = () => {
    const renderProcessAction: ReactElement[] = [];
    renderProcessAction.push(
      <span
        className={styles.btn}
        onClick={() => {
          showActionSheet();
        }}
      >
        <img src={cancelImg} className={styles.btnIcon} alt="" />
        <span className={styles.btnText}>撤销</span>
      </span>
    );
    return renderProcessAction;
  };

  // 显示我的发起-撤销确认模态框
  const showActionSheet = () => {
    const BUTTONS = ['确认', '取消'];
    ActionSheet.showActionSheetWithOptions(
      {
        options: BUTTONS,
        cancelButtonIndex: BUTTONS.length - 1,
        destructiveButtonIndex: BUTTONS.length - 2,
        // title: 'title',
        message: '确认撤销此申请？',
        maskClosable: false
      },
      async (buttonIndex) => {
        if (buttonIndex === 0) {
          console.log('isAction', isAction);
          if (!isAction) {
            isAction = true;
            const isSuccess = await recall();
            if (isSuccess) {
              AppToast({ type: 1, message: '撤销成功' });
              props.onRefreshStatus && props.onRefreshStatus(); // 更新审批状态(详情)
              AppRefresh(); // 更新审批状态(列表)
            }
          }
        } else {
          console.log('cancel');
        }
      }
    );
  };

  const myStatus = props.myStatus;
  let name;
  if (task?.procName.lastIndexOf('申请') === -1) {
    name = task?.procName + '申请';
  } else {
    name = task?.procName;
  }
  const showActionBtn =
    (myStatus === MyStatus.ToApproval &&
      task?.taskStatus === TaskStatus.Approvaling) ||
    (myStatus === MyStatus.MyApply &&
      task?.procStatus === ApprovalStatus.Approvaling);
  return (
    <>
      <Card
        className={
          styles.detail +
          ' globalApprovalDetail' +
          ' ' +
          (!showActionBtn ? styles.noPadding : '')
        }
      >
        <Card.Header
          className={styles.cardHeader}
          title={
            <div className={styles.header}>
              <Image className={styles.image} src={props.task?.sponsorIcon} />
              <span title={task?.procName} className={styles.title}>
                {name}
              </span>
              <span className={ApprovalColor[String(task?.procStatus)]}>
                {task?.procStatusName}
              </span>
            </div>
          }
        >
        </Card.Header>
        <div className={styles.info}>
          {promptText && (
            <div className={styles.promptText}>
              <img src={rejectImg} className={styles.warnIcon} alt="" />
              {promptText}
            </div>
          )}
          <div className={styles.formDetail}>
            <span className={styles.detailTitle}>详细信息</span>
            <ColumnDetail
              label={'申请编号'}
              value={task?.procNo}
            >
            </ColumnDetail>
            <ColumnDetail
              label={'申请人'}
              value={task?.sponsorName}
            >
            </ColumnDetail>
            <ColumnDetail
              label={'申请人部门'}
              value={task?.department}
            >
            </ColumnDetail>
            <ColumnDetail
              label={'申请时间'}
              value={task?.crtTime}
            >
            </ColumnDetail>

            {formParsedG && Object.keys(formParsedG).length > 0 ? (
              <FormRender
                renderMode="detail"
                form={props.form}
                key={task?.procInstId}
                componentClasses={H5Components}
                value={formParsedG}
                formValues={formValuesG}
              />
            ) : null}
          </div>
        </div>
        {historyTaskList ? (
          <ProcessList
            srvTime={props.srvTime}
            historyTask={historyTaskList}
            renderMode="detail"
          />
        ) : null}
        {showActionBtn ? (
          <div className={styles.actionBtn}>
            {myStatus === MyStatus.ToApproval
              ? renderActions()
              : myStatus === MyStatus.MyApply
                ? renderMyApplyActions()
                : undefined}
          </div>
        ) : null}
      </Card>
    </>
  );
};

export default connect()(ApprovalDetail);
